import { Injectable } from '@angular/core';
import { SettingsService } from '@delon/theme';
import { ApiService } from '@srvs/api.service';

@Injectable()
export class SiteService {

  _site: any;
  sites: any[] = [];

  set site(value: any) {
    this._site = value;
    window.sessionStorage.setItem('site', JSON.stringify(value));
  }
  get site(): any {
    try {
      return this._site || JSON.parse(window.sessionStorage.getItem('site'));
    } catch (error) { }
  }

  constructor(
    private apiSrv: ApiService,
    private setSrv: SettingsService
  ) { }

  loadUserSites(): Promise<any> {
    const apiUserSites: string = `/api/users/${this.setSrv.user.id}/sites`;
    return new Promise((resolve: any, reject: any) => {
      this.apiSrv.get(apiUserSites).subscribe((sites: any[]) => {
        this.sites = sites;
        resolve(sites);
      }, reject, reject);
    });
  }

  getSiteById(id: number): any {
    return this.sites.find(item => item.id === id);
  }

  siteToOption(): any[] {
    return SiteService.siteToOption(this.sites);
  }

  siteToTreeOption(): any[] {
    return SiteService.siteToTreeOption(this.sites);
  }

  static siteToOption(sites: any[]): any[] {
    return sites.map(item => <Object>{
      label: `${item.companyNameChs} / ${item.siteName}`,
      value: item.id
    });
  }

  static siteToTreeOption(sites: any[]): any[] {
    let tree: any[] = [],
      category: any = {};
    sites.forEach(item => {
      category[item.companyId] = category[item.companyId] || {
        label: item.companyNameChs,
        value: item.companyId,
        children: []
      };
      category[item.companyId].children.push({
        label: item.siteName,
        value: item.id,
        isLeaf: true
      });
    })
    for (const companyId in category) {
      tree.push(category[companyId]);
    }
    return tree;
  }

}
